package com.libservice.datarepositories

import com.libbase.cast
import com.libbase.datarepository.DataRepository
import com.libbase.datarepository.DataRepositoryInterface
import com.libservice.ServiceManager
import com.libservice.models.AuthModel
import java.util.*

class AuthRepository : DataRepository<AuthModel>(
    ServiceManager.instance.cacheService.globalCache.getObject(
        builder.id,
        AuthModel::class.java
    )
) {
    companion object {
        val builder = object : DataRepositoryInterface.Builder {
            override val id: String = "AuthRepository"

            override fun build(): DataRepositoryInterface {
                return AuthRepository()
            }
        }
    }

    override val id: String
        get() {
            return builder.id
        }

    override fun encode(data: AuthModel): Any {
        return data.toMap()
    }

    override fun decode(data: Any): AuthModel? {
        val map: Map<String, Any> = cast(data) ?: return null
        return AuthModel.create(map)
    }

    override fun save() {
        if (data == null) {
            ServiceManager.instance.cacheService.globalCache.remove(id)
        } else {
            ServiceManager.instance.cacheService.globalCache.setObject(id, data)
        }
    }

    internal fun update(accessToken: String, refreshToken: String, expiredTime: Date) {
        data?.let {
            it.accessToken = accessToken
            it.refreshToken = refreshToken
            it.expiredTime = expiredTime

            set(it)
        }
    }
}